package com.fan.gofast.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ip工具类
 *
 * @author Jack
 */
@Slf4j
public class AgentUtil {

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.length() > 15) {
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }

    public static long ipToLong(String strIp) {
        long[] ip = new long[4];
        // 先找到IP地址字符串中.的位置
        int position1 = strIp.indexOf(".");
        int position2 = strIp.indexOf(".", position1 + 1);
        int position3 = strIp.indexOf(".", position2 + 1);
        // 将每个.之间的字符串转换成整型
        ip[0] = Long.parseLong(strIp.substring(0, position1));
        ip[1] = Long.parseLong(strIp.substring(position1 + 1, position2));
        ip[2] = Long.parseLong(strIp.substring(position2 + 1, position3));
        ip[3] = Long.parseLong(strIp.substring(position3 + 1));
        return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
    }

    // 将十进制整数形式转换成127.0.0.1形式的ip地址
    public static String longToIP(long longIp) {
        StringBuffer sb = new StringBuffer("");
        // 直接右移24位
        sb.append(String.valueOf((longIp >>> 24)));
        sb.append(".");
        // 将高8位置0，然后右移16位
        sb.append(String.valueOf((longIp & 0x00FFFFFF) >>> 16));
        sb.append(".");
        // 将高16位置0，然后右移8位
        sb.append(String.valueOf((longIp & 0x0000FFFF) >>> 8));
        sb.append(".");
        // 将高24位置0
        sb.append(String.valueOf((longIp & 0x000000FF)));
        return sb.toString();
    }

    public static String getIpFromCity(String ip) {
        try {
            String api = "https://open.onebox.so.com/dataApi?type=ip&src=onebox&tpl=0&num=1&query=ip&url=ip&ip=" + ip;
            String resultJson = HttpClient.sendHttpGet(api);
            Map map = (Map) JsonUtil.fromJson(resultJson,Map.class);
            StringBuilder stringBuilder = new StringBuilder();
            if (Objects.nonNull(map.get("1"))) {
                stringBuilder.append(map.get("1"));
            }
            if (Objects.nonNull(map.get("2"))) {
                stringBuilder.append(map.get("2"));
            }
            if (Objects.nonNull(map.get("3"))) {
                stringBuilder.append(map.get("3"));
            }
            return Objects.nonNull(stringBuilder.toString()) ? null : stringBuilder.toString();
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取服务器IP地址
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String getServerIp() {
        String SERVER_IP = null;
        Set<String> ips =new HashSet<>();
        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;

            while (netInterfaces.hasMoreElements()) {

                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                Enumeration addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = (InetAddress) addresses.nextElement();
                    SERVER_IP = ip.getHostAddress();
                    ips.add(SERVER_IP);
                    if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {
                        SERVER_IP = ip.getHostAddress();
                        ips.add(SERVER_IP);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if(ips.contains("127.0.0.1")){
            ips.remove("127.0.0.1");
        }
        List<String> ipsList = ips.stream().filter(t -> !t.contains(":")).collect(Collectors.toList());
        SERVER_IP = ips.isEmpty()?"127.0.0.1":ipsList.get(0);
        return SERVER_IP;
    }
}
